package com.uduemc.biso.node.web.api.udin.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.uduemc.biso.core.extities.pojo.DeployType;
import com.uduemc.biso.node.web.api.exception.NotFoundException;
import com.uduemc.biso.node.web.api.service.ThemeService;
import com.uduemc.biso.node.web.service.DeployService;

import cn.hutool.core.util.NumberUtil;

@Controller
@RequestMapping("/api/udin/module")
public class UModuleController {

	@Autowired
	DeployService deployServiceImpl;

	@Autowired
	ThemeService themeServiceImpl;

	@GetMapping("/official.html")
	public ModelAndView component(HttpServletRequest request, ModelAndView modelAndValue)
			throws NotFoundException, IOException {
		Map<String, Object> addObjectByRequest = getAddObjectByRequest(request);
		if (addObjectByRequest == null) {
			throw new NotFoundException("未能验证该组件页面！");
		}
		modelAndValue.addAllObjects(addObjectByRequest);
		modelAndValue.setViewName("udin/module/official");
		return modelAndValue;
	}

	protected Map<String, Object> getAddObjectByRequest(HttpServletRequest request) throws IOException {
		String nus = request.getParameter("nus");
		if (StringUtils.isBlank(nus)) {
			return null;
		}

		String[] split = nus.split(",");
		for (String nu : split) {
			if (!NumberUtil.isNumber(nu)) {
				return null;
			}
		}

		Map<String, Object> result = new HashMap<>();
		result.put("nus", split);

		String theme = request.getParameter("theme");
		if (StringUtils.isBlank(theme)) {
			theme = "1";
		}

		String color = request.getParameter("color");
		if (StringUtils.isBlank(color)) {
			color = "0";
		}

		result.put("theme", theme);
		result.put("color", color);

		String componentsVersion = deployServiceImpl.localhostVersion(DeployType.COMPONENTS);
		String componentsCss = "/api/deploy/components/dist-udin.css?v=" + componentsVersion;
		String componentsJS = "/api/deploy/components/dist-udin.js?v=" + componentsVersion;
		result.put("componentsCss", componentsCss);
		result.put("componentsJS", componentsJS);

		StringBuilder backendjsSource = themeServiceImpl.makeBackendjsSource();
		result.put("backendjsSource", backendjsSource.toString());

		return result;
	}

}
